import os
import requests
import time
import json
import datetime
from notify import send

##cron: 12 12 5 * *   
##每个月的5号12点12分运行
##new Env("中银尊享有礼")

# 基于当前月份计算活动ID
def get_activity_id():
    # 设置基准月份和ID (2025年7月=55)
    base_year = 2025
    base_month = 7
    base_id = 55
    
    now = datetime.datetime.now()
    # 计算当前月份与基准月份的差值
    months_diff = (now.year - base_year) * 12 + (now.month - base_month)
    return base_id + months_diff

# 获取活动ID
activity_id = get_activity_id()

# 从环境变量获取authorization
authorization = os.environ.get("zy_token")
if not authorization:
    print("⚠️ 环境变量 zy_token 未设置")
    send("中银立减金通知", "⚠️ 环境变量 zy_token 未设置")
    exit(1)
    
# 修正URL：添加f-string格式化
url = f"https://gd.brcloud.bankofchina.com/zxyl/coupon/api/prize/lucky?activity_id={activity_id}"
headers = {
    "Host": "gd.brcloud.bankofchina.com",
    "Connection": "keep-alive",
    "authorization": authorization,
    "charset": "utf-8",
    "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/126.0.6478.188 Mobile Safari/537.36 XWEB/1260117 MMWEBSDK/20221011 MMWEBID/9222 MicroMessenger/8.0.30.2260(0x28001E3B) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android",
    "content-type": "application/json",
    "Accept-Encoding": "gzip,compress,br,deflate",
    "Referer": "https://servicewechat.com/wxc1494f20537c4de6/69/page-frame.html"
}
# 初始化变量
MAX_RUNS = 4  # 定义最大运行次数
results = []
prizes = []  # 初始化奖品列表
for i in range(1, MAX_RUNS + 1):  # 使用MAX_RUNS变量
    try:
        print(f"\n🔄 第 {i} 次抽奖请求中...")
        res = requests.get(url, headers=headers, timeout=10)
        
        # 处理200状态码
        if res.status_code == 200:
            try:
                body = res.json()
                message = body.get("message", "无message字段")
                prize_name = body.get("body", {}).get("prize_name", "未获得奖品")
                
                # 如果获得奖品，添加到prizes列表
                if prize_name != "未获得奖品":
                    prizes.append(prize_name)
                
                result_str = f"第 {i} 次: {message} - 奖品: {prize_name}"
                results.append(result_str)
                print(f"✅ {result_str}")
                
            except json.JSONDecodeError:
                error_msg = f"第 {i} 次: 响应解析失败 - 原始返回: {res.text[:50]}..."
                results.append(error_msg)
                print(f"❌ {error_msg}")
                
        # 处理500状态码
        elif res.status_code == 500:
            try:
                body = res.json()
                message = body.get("message", "无message字段")
                result_str = f"第 {i} 次: 抽奖失败(500) - 消息: {message}"
                results.append(result_str)
                print(f"❌ {result_str}")
                
            except json.JSONDecodeError:
                error_msg = f"第 {i} 次: 500错误响应解析失败 - 原始返回: {res.text[:50]}..."
                results.append(error_msg)
                print(f"❌ {error_msg}")
                
        # 处理其他状态码
        else:
            error_msg = f"第 {i} 次: 请求失败 - 状态码: {res.status_code}"
            results.append(error_msg)
            print(f"❌ {error_msg}")
    
    except Exception as e:
        error_msg = f"第 {i} 次: 请求异常 - {str(e)}"
        results.append(error_msg)
        print(f"❌ {error_msg}")
    
    # 前3次等待10秒，最后一次不等待
    if i < MAX_RUNS:
        print("⏳ 等待10秒后继续...")
        time.sleep(10)
# 汇总抽奖结果
if prizes:
    prize_summary = "🎉 获得立减金: " + "、".join(prizes)
else:
    prize_summary = "😢 本次未获得有效立减金"
# 构建最终结果摘要
summary = (
    f"【中银立减金抽奖结果】\n"
    f"执行次数: {MAX_RUNS}次\n"
    f"活动ID: {activity_id} (自动计算)\n"
    f"{prize_summary}\n\n"
    "📊 详细结果:\n" + "\n".join(results)
)
print("\n" + "="*50)
print(summary)
print("="*50)
# 发送通知
send("中银立减金通知", summary)